package net.sunzc.base.wxapi;


import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.socks.library.KLog;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import net.sunzc.base.R;
import net.sunzc.base.ui.BaseTitleActivity;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

@ContentView(R.layout.activity_wxpay_entry)
public class WXPayEntryActivity extends BaseTitleActivity implements IWXAPIEventHandler {
    private static final int SUCCESS = 0;
    private static final int FAILURE = -1;
    private static final int CANCEL = -2;
    @ViewInject(R.id.tv_pay_success)
    private TextView tv_pay_success;
    @ViewInject(R.id.tv_pay_success_toorder)
    private TextView tv_pay_success_toorder;
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KLog.i(WXPAY_TAG, "微信支付页面开始调用");
        api = WXAPIFactory.createWXAPI(this, WX_PAY_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    private void checkPayResult(int code) {
        switch (code) {
            case SUCCESS:
                Intent intent = new Intent();
                intent.setAction(WX_PAY_SUCCESS_BROADCAST);
                sendBroadcast(intent);
                finish();
                break;
            case FAILURE:
                tv_pay_success.setText("支付失败！错误代码为:" + code);
                break;
            case CANCEL:
                tv_pay_success.setText("您已取消付款！错误代码为:" + code);
                break;
            default:
                break;
        }
    }

    @Override
    public void onReq(BaseReq arg0) {
    }

    @Override
    public void onResp(BaseResp resp) {
        KLog.i(WXPAY_TAG, "errCode = " + resp.errCode + "-错误结果:-" + resp.errStr);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            checkPayResult(resp.errCode);
        }
    }

}
